package yxy.game.pm2.chat.command.player;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.cluster.ClusterBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlayerMessage;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.chat.module.ChatChannel_HomeTown;

/** 玩家 修改地区 */
@MessageType(proto = Command.PlayerRegionChange, classtype = PlayerMessage.PlayerRegionChangeRequest.class)
public class CMD_PlayerRegionChange extends Command<PlayerMessage.PlayerRegionChangeRequest> {

	@Override
	public void execute(MessageSource messageSource, PlayerMessage.PlayerRegionChangeRequest request) {
		String playerCode = messageSource.getTag();
		int region = request.getRegion();
		int city = request.getCity();

		PlayerMessage.PlayerRegionChangeResponse.Builder response = PlayerMessage.PlayerRegionChangeResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		ClusterBean clusterBean = ClusterBean.get(areaBean.getClusterId()); //专服
		try {
			if (playerBean.tryLock()) {
				int oriTown = playerBean.getTown();
				playerBean.setTown(region);
				playerBean.setCity(city);
				playerBean.set();

				// 换频道
				ChatChannel_HomeTown cchome = ChatChannel_HomeTown.get(clusterBean.getClusterId(), oriTown);
				if (cchome != null) {
					cchome.logout(playerBean);
				}
				cchome = ChatChannel_HomeTown.get(clusterBean.getClusterId(), playerBean.getTown());
				if (cchome != null) {
					cchome.register(playerBean);
				}

				response.setRegion(playerBean.getTown());
				response.setCity(playerBean.getCity());
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			playerBean.unlock();
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, PlayerMessage.PlayerRegionChangeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}